//
//  NCChatBaseCell.m
//  AGEmojiKeyboard
//
//  Created by LINAICAI on 2018/4/17.
//

#import "NCChatBaseCell.h"
#import "NSDate+Extension.h"
#import "UIImageView+WebCache.h"
#import "NCChatUserInfoManager.h"

@implementation NCChatBaseCell
- (NSString *)timeStringByTimeStamp:(long long)timeStamp {
    // 公众号的时间戳, 会多1000.
    if (timeStamp > 10000000000) {
        timeStamp = timeStamp/1000;
    }
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    NSDate *createDate = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    if ([createDate wb_isToday]) {
        fmt.dateFormat = @"HH:mm";
        return [fmt stringFromDate:createDate];
    }else if ([createDate wb_isThisYear]){
        
        fmt.dateFormat = @"MM月dd日 HH:mm";
        return [fmt stringFromDate:createDate];
    }else {
        //如果当前时间是12小时制，就会显示08:07
        fmt.dateFormat = @"yyyy年MM月dd日 HH:mm";
        return [fmt stringFromDate:createDate];
    }
}
- (void)setMessage:(NCChatMessage *)message{
    ///保存起来,后面子类可能会用到它的filepath等属性
    _message = message;
    
    ///设置消息状态
    [self setupStatus];
    ///设置消息时间
    if (message.showTime) {
        self.timeLabel.text = [NSString stringWithFormat:@" %@ ",[self timeStringByTimeStamp:[message.date timeIntervalSince1970]]];
    }
    else{
        self.timeLabel.text = @"";
    }
    
    ///异步加载用户数据
    NCChatUser *user =  [[NCChatUserInfoManager shared]getUserCache:message.senderId];
    if (!user) {
        ///如果没有缓存,就从代理拿
        if ([NCChatUserInfoManager shared].delegate && [[NCChatUserInfoManager shared].delegate respondsToSelector:@selector(getUserWith:completion:)]) {
            [[NCChatUserInfoManager shared].delegate getUserWith:message.senderId completion:^(NCChatUser *user) {
                [self updateUser:user];
                ///新的用户,更新到缓存去
                [[NCChatUserInfoManager shared] refreshUserInfoCache:user];
            }];
        }

    }
    else{
        ///有缓存,直接拿来配置用户信息
        [self updateUser:user];
    }

    
    
}
- (void)updateUser:(NCChatUser *)user{
    ///设置消息发送者名字
    self.usrNameLabel.text = user.userName;
    ///设置消息发送者头像
    [self.avatorImage sd_setImageWithURL:[NSURL URLWithString:user.userAvator] placeholderImage:NCChatUIImage(@"avatar_user")];
}
- (void)awakeFromNib {
    [super awakeFromNib];
    ///预设
    self.usrNameLabel.text = @"";
    
    [self.failButton setImage:NCChatUIImage(@"ExclamationMark") forState:UIControlStateNormal];
    [self.failButton addTarget:self action:@selector(failToSendMessage) forControlEvents:UIControlEventTouchUpInside];
    
    [self.indicatorView setHidesWhenStopped:YES];
    
    self.avatorImage.image = NCChatUIImage(@"avatar_user");
    
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    self.timeLabel.textColor = [UIColor lightGrayColor];
    self.timeLabel.layer.cornerRadius = 2.0;
    self.timeLabel.layer.masksToBounds = YES;
    
    self.contentLabel.enabledTextCheckingTypes = NSTextCheckingTypeLink;
    self.contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.contentLabel.lineSpacing = 3;
    self.contentLabel.delegate = self;
    
    
    
    ///监听message的发送状态
    [self addObserver:self forKeyPath:@"message.status" options: NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    //拿到新值/旧值,进行操作
    NSUInteger new = change[@"new"];
    NSUInteger old = change[@"old"];
    if (new == old) {
        
    }
    else{
        [self setupStatus];
    }
    
    
}
- (void)setupStatus{
    
    switch (self.message.status) {
        case NCChatMessageSendSuccess:
        {
            //发送成功
            NSLog(@"NCChatMessageSendSuccess");
            [self.indicatorView stopAnimating];
            [self.failButton setHidden:YES];
        }
            break;
        case NCChatMessageSending:
        {
            NSLog(@"NCChatMessageSending");
            //发送中
            [self.indicatorView startAnimating];
            [self.failButton setHidden:YES];
        }
            break;
        case NCChatMessageSendFail:
        {
            NSLog(@"NCChatMessageSendFail");
            //发送失败
            [self.indicatorView stopAnimating];
            [self.failButton setHidden:NO];
            
        }
            break;
            
        default:
            break;
    }
}
- (void)failToSendMessage{
    //点击失败状态按钮发送通知,告诉控制器有消息失败了
    [[NSNotificationCenter defaultCenter]postNotificationName:NCChatMessageSendFailNotifi object:self.message];
}
- (void)attributedLabel:(TTTAttributedLabel *)label
   didSelectLinkWithURL:(NSURL *)url{
    if ([[UIApplication sharedApplication]canOpenURL:url]) {
        [[UIApplication sharedApplication]openURL:url];
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}
- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"message.status"];
}
@end
